package cn.aws360.boot.base.api.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.CharUtil;
import cn.hutool.http.HttpUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

/**
 * @author junnan
 */
@Slf4j
@UtilityClass
public class FileUtils {

    private static final String TMP = "tmp";

    public static File downFile(String fileUrl, String fileType) {
        File file = null;
        try {
            String filePath = String.format("/%s/%s.%s", TMP, UUID.fastUUID(), fileType);
            file = HttpUtil.downloadFileFromUrl(fileUrl, filePath);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return file;
    }

    public static File convert(MultipartFile multipartFile) {
        File file = null;
        String originalFilename = multipartFile.getOriginalFilename();
        try {
            String[] split = Objects.requireNonNull(originalFilename).split("\\.");
            file = File.createTempFile(TMP + CharUtil.DASHED, "." + split[split.length - 1]);
            multipartFile.transferTo(file);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return file;
    }

}
